//
//  CYWithdrawViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/17.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYWithdrawViewController.h"

#import "CYWithdrawBalanceCell.h"
#import "CYWithdrawSelectCardCell.h"
#import "CYWithdrawLimitCell.h"
#import "CYWithdrawInputCell.h"
#import "CYEmptyCell.h"
#import "CYWithdrawDateCell.h"

#import "CYSelectCardView.h"
#import "CYWithdrawHintCouponView.h"
#import "CYWithdrawHintProjectView.h"

#import "CYDataAPIBankCardModel.h"

#import "CYWithdrawRecordViewController.h"
#import "CYWithdrawSuccessViewController.h"
#import "CYMainController.h"
#import "CYFinanceDetailViewController.h"



@interface CYWithdrawViewController ()

@property(nonatomic, strong)UIView *tableFooterView;
@property(nonatomic, strong)UIButton *submitButton;
@property(nonatomic, strong)UILabel *tipTitleLabel;
@property(nonatomic, strong)UILabel *tipLabel;

@property(nonatomic, strong)CYWithdrawBalanceCellObject *balanceCell;
@property(nonatomic, strong)CYWithdrawSelectCardCellObject *cardCell;
@property(nonatomic, strong)CYWithdrawLimitCellObject *limitCell;
@property(nonatomic, strong)CYWithdrawInputCellObject *inputCell;
@property(nonatomic, strong)CYWithdrawDateCellObject *dateCell;

@property(nonatomic, strong)NSArray *cardList;
@property(nonatomic, strong)CYDataAPIBankCardModel *currentCard;
@property(nonatomic, assign)BOOL loading;

@property(nonatomic, assign)BOOL successed;

@property(nonatomic, strong)NSNumber *couponAmount;
@property(nonatomic, strong)NSNumber *hasPrivilege;
@property(nonatomic, strong)NSNumber *maxInterest;
@property(nonatomic, strong)NSNumber *projectId;
@property(nonatomic, strong)NSNumber *duration;

@end


@implementation CYWithdrawViewController

- (void)close
{
    [MobClick event:UM_EVENT_0063];
    [super close];
}

- (void)loadUI
{
    self.navigationItem.title = @"提现";
    self.tableView.cy_autoLockVertical = YES;
    
    UIButton *recordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    recordButton.tintColor = HEXCOLOR(@"444444");
    [recordButton setTitle:@"提现记录" forState:UIControlStateNormal];
    recordButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [recordButton sizeToFit];
    [recordButton addTarget:self action:@selector(onRecordButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:recordButton];
    
    self.tipLabel = [[UILabel alloc] init];
    self.tipLabel.textColor = HEXCOLOR(@"666666");
    self.tipLabel.font = [UIFont systemFontOfSize:12];
    self.tipLabel.numberOfLines = 0;
    self.tipLabel.text = @"1、平台提现预计到账时间为T+1工作日，遇双休日法定节假日顺延，实际到账时间依据银行存管方及提现银行而有所差异，请您耐心等待。\n2、如本卡丢失、破损及更换，请您联系客服，按照要求提供相关资料。";
    self.tipLabel.size = [self.tipLabel sizeThatFits:CGSizeMake(SCREEN_WIDTH - 40, MAXFLOAT)];
    
    self.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 47 + 136 + self.tipLabel.height)];
    {
        self.submitButton = [UIButton cy_mainButtonWithTitle:@"确认提现"];
        [self.submitButton addTarget:self action:@selector(onSubmitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        self.submitButton.width = self.tableFooterView.width - 40;
        self.submitButton.height = 44;
        self.submitButton.centerX = self.tableFooterView.width / 2;
        self.submitButton.top = 40;
        [self.tableFooterView addSubview:self.submitButton];
        
        self.tipTitleLabel = [[UILabel alloc] init];
        self.tipTitleLabel.text = @"温馨提示：";
        self.tipTitleLabel.font = [UIFont systemFontOfSize:12];
        self.tipTitleLabel.textColor = HEXCOLOR(@"666666");
        [self.tipTitleLabel sizeToFit];
        self.tipTitleLabel.left = 20;
        self.tipTitleLabel.centerY = 118;
        [self.tableFooterView addSubview:self.tipTitleLabel];
        
        self.tipLabel.left = 20;
        self.tipLabel.centerY = self.tableFooterView.height / 2 + 44.5;
        [self.tableFooterView addSubview:self.tipLabel];
    }
    self.tableView.tableFooterView = self.tableFooterView;
    
    [self loadCells];
}

- (void)loadData
{
    @weakify(self);
    [[TCRACObserve(self, currentCard) takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
        @strongify(self);
        if(self.currentCard)
        {
            [CYStandardDataAPI user_preWithdrawalWithBank_id:self.currentCard.id complete:^(CYResponse *response) {
                @strongify(self);
                if(response.code == 0)
                {
                    if([response.content isKindOfClass:[NSDictionary class]])
                    {
                        self.couponAmount = response.content[@"notUseCouponAmount"];
                        self.limitCell.limit = SAFE_NUMBER(response.content[@"mostWithdrawal"]);
                        self.balanceCell.balance = SAFE_NUMBER(response.content[@"walletTotle"]);
                        self.inputCell.limitCount = SAFE_NUMBER(response.content[@"withdrawalCount"]);
                        self.dateCell.date = [SAFE_NUMBER(response.content[@"accountingDate"]) cy_date];
                        self.hasPrivilege = SAFE_NUMBER(response.content[@"hasPrivilege"]);
                        self.maxInterest = SAFE_NUMBER(response.content[@"maxInterest"]);
                        self.projectId = SAFE_NUMBER(response.content[@"projectId"]);
                        self.duration = SAFE_NUMBER(response.content[@"duration"]);
                        [self.tableView reloadData];
                    }
                }
            }];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if(self.successed)
    {
        NSMutableArray *viewControllers = self.navigationController.viewControllers.mutableCopy;
        [viewControllers removeObject:self];
        self.navigationController.viewControllers = viewControllers;
    }
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

- (void)loadDataFromServer
{
    if(self.loading)
    {
        return;
    }
    self.loading = YES;
    if(self.cardList == nil)
    {
        [SVProgressHUD show];
    }
    @weakify(self);
    [CYStandardDataAPI user_queryBindBankCardWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            self.cardList = [CYDataAPIBankCardModel mj_objectArrayWithKeyValuesArray:response.content];
            if(self.currentCard == nil)
            {
                self.currentCard = self.cardList.firstObject;
            }
            else
            {
                BOOL find = NO;
                for(CYDataAPIBankCardModel *model in self.cardList)
                {
                    if([model.id isEqualToNumber:self.currentCard.id])
                    {
                        find = YES;
                        break;
                    }
                }
                if(find)
                {
                    self.currentCard = self.currentCard;
                }
                else
                {
                    self.currentCard = self.cardList.firstObject;
                }
            }
            self.cardCell.bankName = self.currentCard.bankName;
            self.cardCell.cardNumber = [NSString stringWithFormat:@"(尾号%@)", self.currentCard.bankCardNo.cy_suffixCardNumber];
            self.cardCell.bankIcon = self.currentCard.bankIcon;
            
            [self.tableView reloadData];

            [SVProgressHUD dismiss];
        }
        else
        {
            if(self.cardList == nil)
            {
                [SVProgressHUD showErrorWithStatus:@"获取银行卡列表失败"];
            }
            else
            {
                [SVProgressHUD dismiss];
            }
        }
    }];
}

#pragma mark - Action
- (void)selectCardAction
{
    [self.view endEditing:YES];
    @weakify(self);
    CYSelectCardView *view = [[CYSelectCardView alloc] initWithCardList:self.cardList title:@"选择提现银行卡" hasAddButton:NO];
    view.completeAction = ^(CYDataAPIBankCardModel *apiModel) {
        @strongify(self);
        self.currentCard = apiModel;
        self.cardCell.bankName = self.currentCard.bankName;
        self.cardCell.cardNumber = [NSString stringWithFormat:@"(尾号%@)", self.currentCard.bankCardNo.cy_suffixCardNumber];
        self.cardCell.bankIcon = self.currentCard.bankIcon;
        [self.tableView reloadData];
    };
    [view show];
}

- (void)recordAction
{
    CYWithdrawRecordViewController *withdrawRecordViewController = [[CYWithdrawRecordViewController alloc] init];
    [self.navigationController pushViewController:withdrawRecordViewController animated:YES];
}

- (void)submitAction
{
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI user_withdrawalWithAmount:@(self.inputCell.amount.doubleValue) bank_id:self.currentCard.id complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            self.successed = YES;
            CYWithdrawSuccessViewController *withdrawSuccessViewController = [[CYWithdrawSuccessViewController alloc] init];
            withdrawSuccessViewController.date = [SAFE_NUMBER(response.content[@"accountingDate"]) cy_date];
            [self.navigationController pushViewController:withdrawSuccessViewController animated:YES];
            [SVProgressHUD dismiss];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

#pragma mark - Control Events
- (void)onRecordButtonTouchUpInside
{
    [self recordAction];
}

- (void)onSubmitButtonTouchUpInside
{
    if(self.inputCell.amount.length == 0 || self.inputCell.amount.doubleValue <= 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入提现金额"];
        return;
    }
    [self.view endEditing:YES];
    [MobClick event:UM_EVENT_0064];
    
    @weakify(self);
    if(self.hasPrivilege.boolValue)
    {
        CYWithdrawHintProjectView *view = [[CYWithdrawHintProjectView alloc] initWithRate:self.maxInterest due:self.duration amount:@(self.inputCell.amount.doubleValue)];
        view.investAction = ^{
            @strongify(self);
            CYFinanceDetailViewController *financeDetailViewController = [[CYFinanceDetailViewController alloc] init];
            financeDetailViewController.fid = self.projectId;
            [[CYMainController standardController] goFinance];
            [[[CYMainController standardController] financeNavigationController] pushViewController:financeDetailViewController animated:NO];
        };
        view.withdrawAction = ^{
            @strongify(self);
            [self submitAction];
        };
        [view show];
    }
    else if(self.couponAmount.doubleValue > 0)
    {
        CYWithdrawHintCouponView *view = [[CYWithdrawHintCouponView alloc] initWithAmount:SAFE_NUMBER(self.couponAmount)];
        view.couponAction = ^{
            [[CYMainController standardController] goCoupon];
        };
        view.withdrawAction = ^{
            @strongify(self);
            [self submitAction];
        };
        [view show];
    }
    else
    {
        CYWithdrawHintProjectView *view = [[CYWithdrawHintProjectView alloc] initWithRate:self.maxInterest due:self.duration amount:@(self.inputCell.amount.doubleValue)];
        view.investAction = ^{
            @strongify(self);
            CYFinanceDetailViewController *financeDetailViewController = [[CYFinanceDetailViewController alloc] init];
            financeDetailViewController.fid = self.projectId;
            [[CYMainController standardController] goFinance];
            [[[CYMainController standardController] financeNavigationController] pushViewController:financeDetailViewController animated:NO];
        };
        view.withdrawAction = ^{
            @strongify(self);
            [self submitAction];
        };
        [view show];
    }
}

#pragma mark - Private Method
- (void)loadCells
{
    self.balanceCell = [CYWithdrawBalanceCellObject objectWithCellClass:[CYWithdrawBalanceCell class]];
    
    self.cardCell = [CYWithdrawSelectCardCellObject objectWithCellClass:[CYWithdrawSelectCardCell class]];
    
    self.limitCell = [CYWithdrawLimitCellObject objectWithCellClass:[CYWithdrawLimitCell class]];
    
    self.inputCell = [CYWithdrawInputCellObject objectWithCellClass:[CYWithdrawInputCell class]];
    
    self.dateCell = [CYWithdrawDateCellObject objectWithCellClass:[CYWithdrawDateCell class]];
    
    NSMutableArray *cells = [NSMutableArray array];
    {
        [cells addObject:self.balanceCell];
    }
    {
        [cells addObject:self.cardCell];
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        [cells addObject:self.limitCell];
    }
    {
        [cells addObject:self.inputCell];
    }
    {
        [cells addObject:self.dateCell];
    }
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
    self.tableView.dataSource = self.tableModel;
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NICellObject *cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.inputCell)
    {
        CYWithdrawInputCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell.inputTextField becomeFirstResponder];
        return;
    }
    if(cellObject == self.cardCell)
    {
        [self selectCardAction];
        return;
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

@end
